package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleBehaviorMapper;
import com.heima.article.service.ApArticleBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.article.dto.CollectionBehaviorDto;
import com.heima.model.article.pojo.ApCollection;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApArticleBehaviorServiceImpl extends ServiceImpl<ApArticleBehaviorMapper, ApCollection> implements ApArticleBehaviorService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult colection(CollectionBehaviorDto dto) {
        //1.校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user ==null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.查询实体   //user == null ? null : user.getId(), dto.getEquipmentId()
        ApBehaviorEntry apBehaviorEntry = this.behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry ==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.根据实体,查询行为
        ApCollection apCollection = this.getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getEntryId())
                .eq(ApCollection::getEntryId, apBehaviorEntry.getId()));
        if (apCollection==null){
            //收藏
            apCollection = new ApCollection();
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setArticleId(dto.getEntryId());  //dto.getEntryId()
            apCollection.setType((short)0);
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(new Date());
            this.save(apCollection);
        }else{
            //取消收藏
            this.remove(Wrappers.<ApCollection>lambdaQuery()
                    .eq(ApCollection::getArticleId,dto.getEntryId())
                    .eq(ApCollection::getEntryId,apBehaviorEntry.getId()));
        }
        return ResponseResult.okResult();
    }
}
